package com.ahdy.mapper;

import com.ahdy.entity.ElderlyUser;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

// 1. 老人用户Mapper
@Mapper
public interface ElderlyUserMapper {

        // 基础CRUD操作
        @Insert("INSERT INTO elderly_users(password, phone, name, avatar, gender, birthday, " +
                        "allergy_info, status, created_at, updated_at) " +
                        "VALUES(#{password}, #{phone}, #{name}, #{avatar}, #{gender}, #{birthday}, " +
                        "#{allergyInfo}, #{status}, #{createdAt}, #{updatedAt})")
        @Options(useGeneratedKeys = true, keyProperty = "id")
        int insert(ElderlyUser elderlyUser);

        @Update("UPDATE elderly_users SET password=#{password}, phone=#{phone}, name=#{name}, " +
                        "avatar=#{avatar}, gender=#{gender}, birthday=#{birthday}, allergy_info=#{allergyInfo}, " +
                        "status=#{status}, updated_at=#{updatedAt} WHERE id=#{id}")
        int update(ElderlyUser elderlyUser);

        @Delete("DELETE FROM elderly_users WHERE id=#{id}")
        int deleteById(Integer id);

        @Select("SELECT * FROM elderly_users WHERE id=#{id}")
        ElderlyUser findById(Integer id);

        @Select("SELECT * FROM elderly_users")
        List<ElderlyUser> findAll();

        // 业务查询方法
        @Select("SELECT * FROM elderly_users WHERE phone=#{phone}")
        ElderlyUser findByPhone(String phone);

        @Select("SELECT * FROM elderly_users WHERE phone=#{phone} AND password=#{password} AND status='正常'")
        ElderlyUser findByPhoneAndPassword(@Param("phone") String phone, @Param("password") String password);

        @Update("UPDATE elderly_users SET last_login=#{lastLogin} WHERE id=#{id}")
        int updateLastLogin(@Param("id") Integer id, @Param("lastLogin") LocalDateTime lastLogin);

        @Select("SELECT * FROM elderly_users WHERE status=#{status}")
        List<ElderlyUser> findByStatus(ElderlyUser.UserStatus status);

        // 根据子女ID查询关联的老人列表
        List<ElderlyUser> findElderlyByFamilyId(Integer familyId);

        // 统计查询
        @Select("SELECT COUNT(*) FROM elderly_users WHERE status='正常'")
        int countActiveUsers();
}
